# cython: language_level=3
from rectpack import *
AlgoList = ['MaxRectsBl',
            'MaxRectsBssf',
            'MaxRectsBaf',
            'MaxRectsBlsf',
            'SkylineBl',
            'SkylineBlWm',
            'SkylineMwf',
            'SkylineMwfl',
            'SkylineMwfWm',
            'SkylineMwflWm',
            'GuillotineBssfSas',
            'GuillotineBssfLas',
            'GuillotineBssfSlas',
            'GuillotineBssfLlas',
            'GuillotineBssfMaxas',
            'GuillotineBssfMinas',
            'GuillotineBlsfSas',
            'GuillotineBlsfLas',
            'GuillotineBlsfSlas',
            'GuillotineBlsfLlas',
            'GuillotineBlsfMaxas',
            'GuillotineBlsfMinas',
            'GuillotineBafSas',
            'GuillotineBafLas',
            'GuillotineBafSlas',
            'GuillotineBafLlas',
            'GuillotineBafMaxas',
            'GuillotineBafMinas'
            ]

cdef go_rectpack(draw_width, draw_height, rectangles=None):
    if rectangles is None:
        rectangles = []

    # 利用率初始化
    rate = 0
    # 算法初始化
    packers = newPacker()
    alo = None
    maxYNum = 0
    # 循环算法
    for i in AlgoList:
        # 当前算法 画布高度
        yNum = 0
        # 当前算法图片面积
        imageArea = 0
        # 暂定画布高度
        if draw_height == '' or draw_height == 0:
            for r in rectangles:
                if int(r[0]) > int(r[1]):
                    draw_height += int(r[0])
                else:
                    draw_height += int(r[1])
        else:
            draw_height = 99999
        # 定义算法
        packer = newPacker(pack_algo=globals()[i])
        packer.add_bin(draw_width, draw_height)
        # 添加待打包的矩形
        for r in rectangles:
            imageArea += int(r[0]) * int(r[1])
            packer.add_rect(*r)
        # 运行装箱算法，获取打包结果
        packer.pack()
        # 判断算法排列完成数量比原数量少
        if len(rectangles) > len(packer.rect_list()):
            continue
        # 循环单个算法的返回结果也就是
        for b in packer:
            for r in b:
                # imageArea += int(r.width) * int(r.height)
                # 计算当前排列画布高度
                if r.y + r.height > yNum:
                    yNum = r.y + r.height
                    # 计算利用率
            nowRate = (imageArea / (yNum * draw_width)) * 100
            # 取最大利用率
            if nowRate > rate:
                rate = nowRate
                packers = packer
                alo = i
                maxYNum = yNum
    # 输出最优排列方式
    result = "{\"alo\": \""+str(alo)+"\", \"rate\": \""+str(round(rate, 4))+"\", \"maxYNum\": \""+str(maxYNum)+"\", \"rect_list\": \""+str(packers.rect_list())+"\"}"
    return result